package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
)

type handle struct {
	Addr map[string]string
}

var tmp = make(map[string]string)

func (m *handle) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	ip := req.RemoteAddr[:strings.LastIndex(req.RemoteAddr, ":")]
	fmt.Println(ip)
	target := req.URL
	key := req.RequestURI[1:]
	index := strings.Index(key, "/")
	if strings.Contains(key, "/") {
		key = key[0:index]
	}
	addr := m.Addr[key]
	if addr == "" {
		key = tmp[ip]
		addr = m.Addr[key]
	} else {
		tmp[ip] = key
	}
	fmt.Println(key)
	target.Path = strings.Replace(target.Path, "/"+key, "", 1)
	remote, _ := url.Parse(addr)
	req.URL.Path = target.Path
	fmt.Println(req.URL.Path)
	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.ServeHTTP(w, req)
}

func main() {
	conf := NewConfig()
	proxy := &handle{Addr: conf.Addr}
	err := http.ListenAndServe(":"+conf.Port, proxy)
	log.Fatalln(err)
}
